package com.atguigu.szdz.dcsyl.controller;

import com.atguigu.szdz.dcsyl.common.utils.R;
import com.atguigu.szdz.dcsyl.entity.WbDataEntity;
import com.atguigu.szdz.dcsyl.service.YlDataService;
import com.atguigu.szdz.dcsyl.utils.MapperUtils;
import io.swagger.v3.oas.annotations.Operation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/wbData")
public class WbDataController {

    @Autowired
    private YlDataService ylDataService;
    @Autowired
    private MapperUtils mapperUtils;

    /**
     * 获取 文本 数据
     *
     * @param map
     * @return
     */
    @PostMapping("/getWbData")
    public R getWbData(@RequestBody Map<String, Integer> map) {
        //获取井ID
        Integer wellId = map.get("wellId");
        //获取当前页
        Integer currentPage = map.get("currentPage");
        //获取每页显示条数
        Integer pageSize = map.get("pageSize");
        //获取总条数
        String sql = "select count(*) from dc_wbdata where well_id=" + wellId;
        List<Map<String, Object>> contList = mapperUtils.queryBySql(sql);
        Integer total = Integer.parseInt(contList.get(0).get("count").toString());
        //总页数
        Integer totalPage = total % pageSize == 0 ? total / pageSize : total / pageSize + 1;
        //获取数据
        List<Map<String, Object>> qtListData = ylDataService.getWbData(wellId, currentPage, pageSize);
        return R.ok().put("WbListData", qtListData).put("total", total).put("totalPage", totalPage);
    }

    /**
     * 导入文本数据文件
     */
    @Operation(summary = "导入文本数据文件并解析")
    @PostMapping("/importFile")
    public R importWbData(@RequestParam("file") MultipartFile file, @RequestParam("well_id") Integer wellId) {
        //先去数据库查询是否有该井
        String sql = "select * from dc_well_info where id=" + wellId;
        List<Map<String, Object>> wellList = mapperUtils.queryBySql(sql);
        if (wellList.size() == 0) {
            return R.error("该井不存在");
        }
        if (file.isEmpty()) {
            return R.error("文件不能为空");
        }
        String fileName = file.getOriginalFilename();
        if (fileName == null || !fileName.endsWith(".txt")) {
            return R.error("文件格式错误");
        }
        List<String> lines = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(file.getInputStream(), StandardCharsets.UTF_8))) {

            String line;
            while ((line = reader.readLine()) != null) {
                //过滤空行（避免解析空数据）
                if (line.trim().isEmpty()) {
                    continue;
                }
                lines.add(line.trim());
            }
            //解析数据
            List<WbDataEntity> list = new ArrayList<>();
            for (int i = 2;i<lines.size();i++){
                String line1 = lines.get(i);
                String[] fields = line1.split("\\s+");
                //字段赋值
                WbDataEntity data = new WbDataEntity();
                try {
                    data.setMeasured(Double.valueOf(fields[0]));
                    data.setLncl(Double.valueOf(fields[1]));
                    data.setAzimuth(Double.valueOf(fields[2]));
                    data.setTvd(Double.valueOf(fields[3]));
                    data.setDisplNs(Double.valueOf(fields[4]));
                    data.setDisplEw(Double.valueOf(fields[5]));
                    data.setVertical(Double.valueOf(fields[6]));
                    data.setClosureDistance(Double.valueOf(fields[7]));
                    data.setClosureAzimuth(Double.valueOf(fields[8]));
                    data.setDls(Double.valueOf(fields[9]));
                    data.setEasting(Double.valueOf(fields[10]));
                    data.setNorthing(Double.valueOf(fields[11]));
                    if (fields.length > 12) {
                        data.setComments(fields[12].trim().isEmpty() ? "" : fields[12].trim());
                    } else {
                        data.setComments(""); // 字段缺失时，comments存空字符串
                    }
                    list.add(data);
                }catch (NumberFormatException  e){
                    log.warn("第{}行数据类型转换错误，跳过该行：{}", i + 1, line);
                    continue;
                }
            }
            return R.ok("导入成功").put("wbListData",list);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("文件导入失败");
        }
    }
    /**
     * 导入文本数据
     */
    @Operation(summary = "导入文本数据")
    @PostMapping("/importWbData")
    public R importWbData(@RequestBody Map<String, Object> map) {
        //获取井ID
        Integer wellId = Integer.parseInt(map.get("wellId").toString());
        //获取数据vo->po
        List<WbDataEntity> list = new ArrayList<>();
        //获取数据
        List<Map<String, Object>> wbDataList = (List<Map<String, Object>>) map.get("wbDataList");
        for (Map<String, Object> wbDataMap : wbDataList) {
            WbDataEntity wbDataEntity = new WbDataEntity();
            //转换
            wbDataEntity.setMeasured(wbDataMap.get("measured") != null ? Double.parseDouble(wbDataMap.get("measured").toString()) : null);
            wbDataEntity.setLncl(wbDataMap.get("lncl") != null ? Double.parseDouble(wbDataMap.get("lncl").toString()) : null);
            wbDataEntity.setAzimuth(wbDataMap.get("azimuth") != null ? Double.parseDouble(wbDataMap.get("azimuth").toString()) : null);
            wbDataEntity.setTvd(wbDataMap.get("tvd") != null ? Double.parseDouble(wbDataMap.get("tvd").toString()) : null);
            wbDataEntity.setDisplNs(wbDataMap.get("displNs") != null ? Double.parseDouble(wbDataMap.get("displNs").toString()) : null);
            wbDataEntity.setDisplEw(wbDataMap.get("displEw") != null ? Double.parseDouble(wbDataMap.get("displEw").toString()) : null);
            wbDataEntity.setVertical(wbDataMap.get("vertical") != null ? Double.parseDouble(wbDataMap.get("vertical").toString()) : null);
            wbDataEntity.setClosureDistance(wbDataMap.get("closureDistance") != null ? Double.parseDouble(wbDataMap.get("closureDistance").toString()) : null);
            wbDataEntity.setClosureAzimuth(wbDataMap.get("closureAzimuth") != null ? Double.parseDouble(wbDataMap.get("closureAzimuth").toString()) : null);
            wbDataEntity.setDls(wbDataMap.get("dls") != null ? Double.parseDouble(wbDataMap.get("dls").toString()) : null);
            wbDataEntity.setEasting(wbDataMap.get("easting") != null ? Double.parseDouble(wbDataMap.get("easting").toString()) : null);
            wbDataEntity.setNorthing(wbDataMap.get("northing") != null ? Double.parseDouble(wbDataMap.get("northing").toString()) : null);
            wbDataEntity.setComments(wbDataMap.get("comments") != null ? wbDataMap.get("comments").toString() : null);
            list.add(wbDataEntity);
        }
        //删除旧数据
        ylDataService.removeWbData(wellId);
        //批量插入数据
        ylDataService.saveBatchWb(list,wellId);
        return R.ok("导入成功");
    }
}
